package leetCode.q94;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class S1 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();

        if (root == null) {
            return res;
        }

        TreeNode node = root;

        Deque<TreeNode> stack = new LinkedList<TreeNode>();

        while (node != null || !stack.isEmpty()) {
            // 重复向左走到头，访问并回溯
            while (node != null) {
                stack.push(node);
                node = node.left;
            }
            // 回溯
            node = stack.pop();
            // 访问
            res.add(node.val);

            node = node.right;
        }
        return res;
    }
}
